package tliasmanagement.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import tliasmanagement.utils.CurrentHolder;
import tliasmanagement.utils.JwtUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1.获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();

        // 2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3.获取请求头中的令牌（token）
        String jwt = request.getHeader("token");
        System.out.println("jwt:" + jwt);

        // 4.判断令牌是否存在，如果存在，则通过，如果不存在，则拦截
        if (jwt == null || jwt.isEmpty()){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        // 5.解析token，如果解析失败，响应401
        try {
            Claims claims = JwtUtils.parseJwt(jwt);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId); //存入
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        // 6.放行
        filterChain.doFilter(request, response);

        //7. 删除ThreadLocal中的数据
        CurrentHolder.remove();
    }
}
